package com.wjw.java.io.outputStream_;

import com.wjw.java.io.Students;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;

/**
 * 对象输出流：需要序列化,实现Serializable接口
 */
public class ObjectOutputStream_ {

    public static void main(String[] args) {
        //序列化后,保存的格式不是存文本,而是按照他的格式来保存
        String filePath = "f:\\IO\\data.dat";
        ObjectOutputStream oos = null;
        try {
            //保存基本数据类型
            oos = new ObjectOutputStream(new FileOutputStream(filePath));
            oos.writeInt(100);//int ->Integer(实现了Serializable)
            oos.writeBoolean(true);//boolean ->Boolean(实现了Serializable)
            oos.writeChar('a');//char ->Character(实现了Serializable)
            oos.writeDouble(9.9);//double ->Double(实现了Serializable)
            oos.writeUTF("你好啊");//String(实现了Serializable)

            //保存对象
            Students student = new Students(1L,"张三",199.9d,"static修饰的属性不被序列化","transient修饰的属性不被序列化");
            oos.writeObject(student);
            System.out.println("保存数据完毕...");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(oos != null){
                try {
                    //关闭流的外层即可,底层会关闭FileOutputStream
                    oos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}
